package com.bosssoft.user.permission.center.serve.service.impl;

import com.bosssoft.user.permission.center.serve.dao.entity.SubSystem;
import com.bosssoft.user.permission.center.serve.dao.mapper.SubSystemMapper;
import com.bosssoft.user.permission.center.serve.pojo.dto.Id;
import com.bosssoft.user.permission.center.serve.pojo.dto.IdVersion;
import com.bosssoft.user.permission.center.serve.pojo.dto.SubSystemDTO;
import com.bosssoft.user.permission.center.serve.pojo.query.SubSystemQuery;
import com.bosssoft.user.permission.center.serve.service.SubSystemService;
import com.bosssoft.user.permission.center.serve.util.LoginTokenUtil;
import com.bosssoft.user.permission.center.serve.util.SubSystemBeanUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.page.PageMethod;
import common.annotation.ApiLog;
import common.annotation.AutoFill;
import common.annotation.OperationType;
import common.constant.GlobalConstant;
import common.data.commonresponse.CommonPage;
import common.exception.code.BizErrorCode;
import common.exception.parse.BusinessException;
import common.util.IdGeneratorUtil;
import common.util.MyBeanUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.List;

/**
 * @className: SubSystemServiceImpl
 * @description: 子系统管理业务的具体实现
 * @author: lanyukai
 * @date: 2024/6/13 10:28
 * @since 1.0
 **/
@Validated
@Service
@Slf4j
public class SubSystemServiceImpl implements SubSystemService {
    /**
     *  子系统id
     */
    private static final String PROPERTY_ID="id";
    /**
     *  子系统版本
     */
    private static final String PROPERTY_VERSION="version";
    /**
     *  子系统名列
     */
    private static final String PROPERTY_NAME="name";
    /**
     * 子系统编码列
     */
    private static final String PROPERTY_CODE="code";
    /**
     *  子系统备注列
     */
    private static final String PROPERTY_MARK="remark";
    @Resource
    private SubSystemMapper subSystemMapper;
    @Resource
    private IdGeneratorUtil idGeneratorUtil;
    @ApiLog
    @Override
    public CommonPage<SubSystemDTO> selectSubSystemWithQuery(SubSystemQuery subSystemQuery) {
        Example subSystemExample = new Example(SubSystem.class);
        Example.Criteria subSystemExampleCriteria = subSystemExample.createCriteria();
        if(!StringUtils.isEmpty(subSystemQuery.getName())){
            subSystemExampleCriteria.andLike(PROPERTY_NAME, "%" + subSystemQuery.getName().trim() + "%");
        }
        if(!StringUtils.isEmpty(subSystemQuery.getCode())){
            subSystemExampleCriteria.andLike(PROPERTY_CODE, "%" + subSystemQuery.getCode().trim() + "%");
        }
        if(!StringUtils.isEmpty(subSystemQuery.getRemark())){
            subSystemExampleCriteria.andLike(PROPERTY_MARK, "%" + subSystemQuery.getRemark() + "%");
        }
        /*构建分页列表*/
        PageMethod.startPage(subSystemQuery.getPageIndex(), subSystemQuery.getPageSize());
        Page<SubSystem> subSystemPage = (Page<SubSystem>) subSystemMapper.selectByExample(subSystemExample);
        //复制子系统分页信息到列表中
        List<SubSystemDTO> subSystemDTOList = MyBeanUtil.copyList(subSystemPage, SubSystemDTO::new, null);
        log.debug(String.format("pageNum=%d,pages=%d,total=%d,pageSize=%d ", subSystemPage.getPageNum(), subSystemPage.getPages(), subSystemPage.getTotal(), subSystemPage.getPageSize()));
        return new CommonPage<>(subSystemPage. getTotal(), subSystemPage.getPageNum(), subSystemPage.getPageSize(), subSystemPage.getPages(), subSystemDTOList);
    }

    @ApiLog
    @Override
    public SubSystemDTO selectSubSystemById(Long id) {
        SubSystem subSystem = subSystemMapper.selectByPrimaryKey(id);
        return MyBeanUtil.copyProperties(subSystem, SubSystemDTO::new);
    }

    @ApiLog
    @AutoFill(OperationType.INSERT)
    @Override
    public Boolean addSubSystem(@NotNull @Valid SubSystemDTO subSystemDTO) {
        //DTO注入实体
        SubSystem subSystem = MyBeanUtil.copyProperties(subSystemDTO, SubSystem::new);
        //判断新增的子系统编号是否重复
        Example subSystemExample = new Example(SubSystem.class);
        subSystemExample.createCriteria().andEqualTo(PROPERTY_CODE, subSystem.getCode());
        if(!subSystemMapper.selectByExample(subSystemExample).isEmpty()){
            throw new BusinessException(BizErrorCode.DATA_INSERT_FOUND_NO_UNIQUE_RECORD, "子系统编号重复");
        }
        //设置子系统id
        subSystem.setId(idGeneratorUtil.snowflakeId());
        //设置租户id
        subSystem.setTenantId(LoginTokenUtil.parseTokenToLoginDTO().getTenantId());
        //子系统状态初始不可用
        subSystem.setStatus(GlobalConstant.ROW_DATA_STATUS_INACTIVE);
        return subSystemMapper.insert(subSystem) > 0;
    }

    @ApiLog
    @Override
    public Boolean copySubSystem(@NotNull @Valid Id[] ids) {
        for(Id idItem : ids){
            SubSystem subSystem = subSystemMapper.selectByPrimaryKey(Long.parseLong(idItem.getId()));
            if(subSystem == null){
                throw new BusinessException(BizErrorCode.DATA_SEARCH_NOT_FOUND, "没有对应记录");
            }
            subSystem.setId(idGeneratorUtil.snowflakeId());
            if(subSystemMapper.insert(subSystem) <= 0){
                throw new BusinessException(BizErrorCode.DATA_INSERT_FOUND_NO_UNIQUE_RECORD, "子系统复制出现异常");
            }
        }
        return Boolean.TRUE;
    }

    @Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED)
    @AutoFill(OperationType.UPDATE)
    @ApiLog
    @Override
    public Boolean updateSubSystem(SubSystemDTO subSystemDTO) {
        SubSystem subSystem = subSystemMapper.selectByPrimaryKey(subSystemDTO.getId());
        //DTO注入实体
        SubSystemBeanUtil.copySubSystemDTO2Entity(subSystemDTO, subSystem);
        //修改记录，如果没有记录被修改则抛出异常
        if(subSystemMapper.updateByPrimaryKey(subSystem) <= 0){
            throw new BusinessException(BizErrorCode.DATA_UPDATE_DUE_DUPLICATE_RECORD, "没有记录被修改");
        }
        return Boolean.TRUE;
    }

    @Override
    public Boolean deleteSubSystemById(Long id) {
        return subSystemMapper.deleteByPrimaryKey(id) > 0;
    }

    @Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED)
    @ApiLog
    @Override
    public Boolean deleteSubSystemByIds(Id[] ids) {
        // 在事务中启用批量删除
        for(Id idItem : ids){
            long id = Long.parseLong(idItem.getId());
            if (subSystemMapper.deleteByPrimaryKey(id)<=0){
                throw new BusinessException(BizErrorCode.DATA_DELETE_NOT_FOUND,"当前行的id没匹配到记录");
            }
        }
        return Boolean.TRUE;
    }

    @Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED)
    @ApiLog
    @Override
    public Boolean setSubSystemStatus(long id) {
        SubSystem subSystem = subSystemMapper.selectByPrimaryKey(id);

        if(subSystem == null) {
            throw new BusinessException(BizErrorCode.DATA_SEARCH_NOT_FOUND, "没有找到数据");
        }
        //子系统停用，则启用子系统
        if(subSystem.getStatus().equals(GlobalConstant.ROW_DATA_STATUS_INACTIVE)){
            subSystem.setStatus(GlobalConstant.ROW_DATA_STATUS_ACTIVE);
            subSystemMapper.updateByPrimaryKey(subSystem);
            return true;
        }else{
            //子系统处于启用中，禁止停用
            return false;
        }
    }
}
